from utils import log_info, log_debug
from typing import List, Dict, Any
from dao.exam_statistics_dao import ExamStatisticsDAO


class ExamStatisticsService:
    """考试统计服务类，处理考试统计相关的业务逻辑"""

    def __init__(self):
        """初始化ExamStatisticsService"""
        self.exam_statistics_dao = ExamStatisticsDAO()

    def get_exam_data(self, user_id: int, category: str = None, time_range: str = '7days') -> List[Dict[str, Any]]:
        """
        获取用户的考试数据
        :param user_id: 用户ID
        :param category: 考试类别 ('A', 'B', 'C' 或 None表示全部)
        :param time_range: 时间范围 ('7days', '30days', '180days')
        :return: 考试数据列表
        """
        return self.exam_statistics_dao.get_exam_data(user_id, category, time_range)

    def calculate_statistics(self, exam_data: List[Dict[str, Any]]) -> Dict[str, Any]:
        """
        计算考试统计数据
        :param exam_data: 考试数据列表
        :return: 统计结果字典
        """
        log_debug(f"开始计算考试统计数据，共 {len(exam_data)} 条记录")

        if not exam_data:
            log_debug("没有找到考试数据，返回默认统计结果")
            return {
                'max_score': 0,
                'latest_score': 0,
                'latest_duration': 0,
                'avg_pass_rate': 0,
                'total_exams': 0
            }

        # 计算最高分
        max_score = max(exam['score'] for exam in exam_data)

        # 最新一次成绩
        latest_exam = exam_data[-1]
        latest_score = latest_exam['score']
        latest_duration = latest_exam['duration_seconds']  # 保留原始秒数

        # 计算考试通过的比例
        # 从main.py的配置中获取通过分数标准
        exam_config = {
            'A': {'pass_score': 30},
            'B': {'pass_score': 45},
            'C': {'pass_score': 70}
        }

        # 计算通过的考试次数
        passed_exams = 0
        for exam in exam_data:
            category = exam['category']
            if category in exam_config and exam['score'] >= exam_config[category]['pass_score']:
                passed_exams += 1
            elif exam['score'] >= 60:  # 默认通过分数为60分
                passed_exams += 1

        # 计算通过率
        pass_rate = (passed_exams / len(exam_data)) * 100
        avg_pass_rate = pass_rate

        log_debug(f"考试统计计算完成: 最高分={max_score}, 最新分数={latest_score}, 平均通过率={avg_pass_rate}%")
        return {
            'max_score': round(max_score, 2),
            'latest_score': round(latest_score, 2),
            'latest_duration': round(latest_duration, 2),
            'avg_pass_rate': round(avg_pass_rate, 2),
            'total_exams': len(exam_data)
        }